import axios from 'axios'
import configApi from "@/config/index.js";
import {ElMessage} from "element-plus";
import {getStorageItem} from "@/utils/storage.js";

const NET_ERROR = '网络错误，请稍后再试'

const service = axios.create({
    baseURL: configApi.baseURL,
    timeout: 8000
})

// 请求拦截器
service.interceptors.request.use(config => {
    if (getStorageItem('token')) {
        config.headers.Authorization = 'Bearer ' + getStorageItem('token')
    }
    return config
})

// 响应拦截器
service.interceptors.response.use(async response => {
    const {code, data, msg} = response.data
    if (code === 200) {
        return response.data
    } else if (code === 40001) {
        ElMessage.error(msg)
        return Promise.reject(msg)
    } else if (code === 50001) {
        // location.reload()
    }else {
        ElMessage.error(msg || NET_ERROR)
        return Promise.reject(msg || NET_ERROR)
    }
}, error => {
    ElMessage.error(error.message)
    return Promise.reject(error.message)
})

const request = options => {
    // 如果没有传mock，默认为config中的mock
    let mock = options.mock !== undefined ? options.mock : configApi.mock
    // 如果没有传method，默认为get
    options.method = options.method || 'get'
    // 如果是get请求，就将data放到params中
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    let baseApi
    // 做一层保障，如果是生产环境，就将baseApi设置为线上地址
    if (configApi.env === 'prod') {
        baseApi = configApi.baseApi
    } else {
        // 如果是开发环境或者，就判断是否开启了mock 如果开启了mock，就将baseApi设置为mock地址，否则就设置为线上地址
        baseApi = mock ? configApi.mockApi : configApi.baseApi
    }

    service.defaults.baseURL = baseApi
    return service(options)
}

export default request
